"use client";

import { useEffect, useState } from "react";
import { DownloadImg, GetSignImg } from "@/app/api/operation/query";
import { Button, message, Select } from "antd";
import { VscError } from "react-icons/vsc";

interface Img {
  value: number;
  label: string;
  url: string;
}

interface ImgSource {
  value: number;
  img: any;
}

interface props {
  docid: string;
  onCancle: () => void;
}

export default function Download(props: props) {
  const [datasource, setDataSource] = useState<Img[]>([]);
  const [ImgSource, setImgSource] = useState<ImgSource[]>([]);
  const [imgUrl, setImgUrl] = useState("");
  const [alt, setalt] = useState("");

  useEffect(() => {
    GetSignImg(props.docid).then((res: any) => {
      if (typeof res === "string") {
        message.info("無簽名記錄！");
      } else {
        const temp: Img[] = [];
        for (let i = 0; i < res[0].length; i++) {
          temp.push({
            value: i + 1,
            label: res[0][i].sign_name,
            url: res[0][i].url,
          });
        }
        setDataSource(temp);
      }
    });
  }, [props]);

  const download = async (e: number) => {
    const selOne = datasource.filter((item) => item.value === e)[0];
    setalt(selOne.label);
    try {
      if (!ImgSource.some((item) => item.value === e)) {
        const res: any = await DownloadImg(selOne.url);
        const mimeType = "image/png"; // 需自行實現文件類型判斷

        // 通用渲染方式
        const dataUrl = `data:${mimeType};base64,${res.content}`;
        setImgUrl(dataUrl);
        setImgSource([...ImgSource, { value: e, img: dataUrl }]);
        setalt(selOne.label);
      } else {
        setImgUrl(ImgSource.filter((item) => item.value === e)[0].img);
      }
    } catch  {
      message.info('未找到簽名記錄，請聯繫系統管理員');
    }
  };

  return (
    <>
      <Select
        onChange={(e) => download(e)}
        options={datasource}
        style={{ width: "300px" }}
      ></Select>
      <div
        style={{
          background: "gray",
          width: 500,
          height: 250,
          margin: "20px auto",
          borderRadius: "3px",
        }}
      >
        <img src={imgUrl} alt={alt} style={{width:500,height:250}}></img>
      </div>
      <div style={{ textAlign: "center" }}>
        <Button
          type="primary"
          danger
          shape="circle"
          onClick={() => {
            setImgSource([]);
            setImgUrl('')
            setDataSource([])
            props.onCancle();
          }}
          icon={<VscError></VscError>}
        ></Button>
      </div>
    </>
  );
}
